<template>
  <div id="container">
    <span />
  </div>
</template>

<script setup>
import {ref, watch, onMounted, onBeforeUnmount} from 'vue'
import {CountUp} from 'countup.js'
import {isFunc} from '@/utils/type'

// eslint-disable-next-line
const emits = defineEmits(['ready'])
// eslint-disable-next-line
const props = defineProps({
  delay: {
    type: Number,
    default: 0,
  },
  endVal: {
    type: Number,
    required: true,
  },
  options: {
    type: Object,
  },
  element: {
    default: null,
    required: true
  }
})

const instance = ref(null)

onMounted(() => {
  create()
})
onBeforeUnmount(() => {
  destroy()
})

watch(() => props.delay, newVal => {
  const instanceVal = instance.value
  if (instanceVal && isFunc(instanceVal.update)) {
    instanceVal.update(newVal)
  }
})

function create() {
  if (instance.value) return
  console.log(props)
  // const el = document.getElementById('container')
  const p = props
  const dom = p.element
  const countUpInstance = new CountUp(
    dom,
    p.endVal,
    p.options
  )

  console.log('countUpInstance----', countUpInstance)

  if (countUpInstance.error) return
  instance.value = countUpInstance
  if (p.delay < 0) {
    emits('ready', countUpInstance, CountUp)
    return
  }
  setTimeout(() => countUpInstance.start(() => emits('ready', countUpInstance, CountUp)), p.delay)
}
function destroy() {
  instance.value = null
}
function printValue(value) {
  const instanceVal = instance.value
  if (instanceVal && isFunc(instanceVal.printValue)) {
    return instanceVal.printValue(value)
  }
}
function start(callback) {
  const instanceVal = instance.value
  if (instanceVal && isFunc(instanceVal.start)) {
    return instanceVal.start(callback)
  }
}
function pauseResume() {
  const instanceVal = instance.value
  if (instanceVal && isFunc(instanceVal.pauseResume)) {
    return instanceVal.pauseResume()
  }
}
function reset() {
  const instanceVal = instance.value
  if (instanceVal && isFunc(instanceVal.reset)) {
    return instanceVal.reset()
  }
}
function update(newEndVal) {
  const instanceVal = instance.value
  if (instanceVal && isFunc(instanceVal.update)) {
    return instanceVal.update(newEndVal)
  }
}

// eslint-disable-next-line no-undef
defineExpose({printValue, start, pauseResume, reset, update})
</script>
